var express = require('express');
var router= express.Router();

var cn_14ch = require('./14ch/index');
var top_14th = require('./14th/index');
var cn_14ch_comic = require('./14ch/comic');
router.all('/*',function(req,res,next){
    console.log('调用api');
    next();
});
var rantext='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=-';
router.post('/setCookie',function(req,res,next){
    var temp;
    if(req.cookies){
        temp = req.cookies.user;
    }
    console.log('temp:'+temp);
    if(temp&&temp.length===10){
        console.log('已有cookie' + temp);
        res.cookie("user", temp, {maxAge: 1000*60*60*24*30,httpOnly: true});
        res.json({
            user:{
                username:'访客',
                code:temp
            }
        });
    }else{
        console.log(1);
        var ranstring='';
        for(var i=0;i<10;i++){
            var ran=Math.floor(Math.random()*rantext.length);
            ranstring+=rantext.substr(ran,1);
        }
        console.log(ranstring);
        //设置cookie，配置signed: true的话可以配置签名cookie
        res.cookie("user", ranstring, {maxAge: 1000*60*60*24*30,httpOnly: true}); //, signed: true
        console.log('赠与用户名'+ranstring);
        res.json({user:
            {
                username:'访客',
                code:ranstring
            }
        });
    }
});
router.get('/14ch/comic/pic/*',function(req,res,next){
    console.log('图片请求');
    cn_14ch_comic.getpic(req.url.replace('/14ch/comic/pic','').split('?')[0],req.query,res);
    // next();
})
router.all('/14ch/comic/*',function(req,res,next){
    console.log('Comic Api');
    cn_14ch_comic.route(req.url.replace('/14ch/comic/',''),req,res);
});
router.all('/14ch/*',function(req,res,next){
    console.log('调用14ch.cn api');
    cn_14ch.route(req.url.replace('/14ch/',''),req,res);
});
router.all('/14th/*',function(req,res,next){
    console.log('调用14th.top api');
    top_14th.route(req.url.replace('/14th/',''),req.body,res);
});

module.exports=router;